const {
  MemberModel
} = require('../../../utils/member-model.js');
var memberModel = new MemberModel();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: 0,
    couponData: [],
    isHints: false, //无数据提示信息
    disabled: false,
    assetId: '',
    selectShopId: '',
    pageIndex: 1,
    pageSize: 10,
    pageCount: 1,
    loadText: "",
    isLoadData: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},
  /**
   * 查询不同状态的券
   */
  selectStateCoupon: function (e) {
    var type = e.currentTarget.dataset.type; //页面类型
    this.setData({
      couponData: [],
      type: type,
      isHints: false,
      assetId: '',
      selectShopId: '',
      pageIndex: 1,
      pageCount: 1,
      loadText: "",
      isLoadData: false,
    }, function () {
      this.getUserDiscountCoupon(type);
    })
  },
  /**
   * 优惠券列表
   */
  getUserDiscountCoupon: function (type) {
    var that = this;
    var param = {};
    param.merchantId = wx.getStorageSync('merchantId');
    param.assetStatus = type; //0未使用 2已失效
    param.offset = (that.data.pageIndex - 1) * that.data.pageSize;
    param.limit = that.data.pageSize;
    memberModel.userDiscountCoupon(param).then(data => {
      if (data) {
        let pageCountTotal = data.totalCount % that.data.pageSize == 0 ? (data.totalCount / that.data.pageSize) : (parseInt(data.totalCount / that.data.pageSize) + 1);
        that.setData({
          pageCount: pageCountTotal
        })
        if (data.totalCount > 0) {
          var dataList = [];
          for (var i = 0; i < data.data.length; i++) {
            let item = data.data[i];
            var list = {};
            list.couponName = item.couponName ? item.couponName : "-";
            list.validBegin = item.validBegin ? item.validBegin.replace(/-/g, "/") : "";
            list.validEnd = item.validEnd ? item.validEnd.replace(/-/g, "/") : "";
            list.giftCoinNum = item.promotionAmount ? item.promotionAmount : "0" || "0"; //赠币数
            list.discountNum = item.promotionAmount ? item.promotionAmount.toFixed(1) : "0.0" || "0.0"; //折扣数
            list.promotionAmount = item.promotionAmount ? item.promotionAmount.toFixed(2) : "0.00" || "0.00"; //满减金额
            var promotionAmount = list.promotionAmount.split(".");
            list.integer = promotionAmount[0];
            list.decimals = promotionAmount[1];
            list.couponType = item.couponType;
            list.accumAmount = item.accumAmount ? item.accumAmount : 0; //满额数量
            list.maxAmount = item.maxAmount ? item.maxAmount : 0; //最高消费数额
            list.discountLimit = item.discountLimit ? item.discountLimit : 0; //最高折扣金额
            list.assetStatus = parseInt(item.assetStatus); //资产状态 0:未使用 1:已使用 2:已过期
            list.assetId = item.assetId;
            list.channels = item.channels; //渠道
            list.svipType = item.svipType; //SVIP类型 1:是 0:否
            list.shopId = item.shopId; //门店id
            list.availableShopName = item.availableShopName;
            dataList.push(list);
          }
          // 将新一页的数据添加到原数据后面
          var couponDataList = this.data.couponData;
          var newData = couponDataList.concat(dataList);
          that.setData({
            isLoadData: false,
            isHints: false,
            couponData: newData
          })
        } else {
          that.setData({
            couponData: [],
            isHints: true
          })
        }
      }
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 立即领取优惠券
   */
  getCoupon: function (event) {
    let that = this;
    if (!that.data.disabled) {
      that.setData({
        disabled: true,
      })
      var assetId = event.currentTarget.dataset.id; //页面类型
      var shopId = event.currentTarget.dataset.shop; //页面类型
      if (shopId == '*') {
        that.setData({
          disabled: false,
        })
        wx.navigateTo({
          url: `/pages/memberCenter/nearbyShop/index?assetId=${assetId}`
        })
      } else {
        if (shopId != '' && shopId != null) {
          that.setData({
            assetId: assetId,
            selectShopId: shopId
          }, function () {
            that.bindCoupon()
          })
        } else {
          that.setData({
            disabled: false,
          })
          wx.showToast({
            title: `没有找到匹配的门店`,
            icon: 'none',
            duration: 2000
          })
        }
      }
    }
  },

  /**
   * 绑定优惠券
   */
  bindCoupon: function () {
    let that = this;
    if (that.data.assetId) {
      memberModel.userCouponUse({
        merchantId: wx.getStorageSync('merchantId'),
        shopId: that.data.selectShopId, //门店Id
        type: 0,
        assetId: that.data.assetId, //资产id
        channel: 0
      }).then(data => {
        wx.showToast({
          title: `优惠券领取成功！`,
          icon: 'none',
          duration: 2000,
        })
        that.setData({
          disabled: false,
        })
        setTimeout(function () {
          that.setData({
            couponData: [],
            isHints: false,
            assetId: '',
            selectShopId: '',
            pageIndex: 1,
            pageCount: 1,
            loadText: "",
            isLoadData: false,
          })
          that.getUserDiscountCoupon(0);
        }, 1000)
      }).catch(err => {
        that.setData({
          disabled: false,
        })
        wx.showToast({
          title: `${err.error}`,
          icon: 'none',
          duration: 2000
        })
      })
    }
  },


  /**
   * 滚动到底部/右边时触发
   */
  scrollEnd: function () {
    let that = this;
    that.setData({
      pageIndex: that.data.pageIndex + 1,
      isLoadData: true,
      loadText: "加载中..."
    }, function () {
      if (that.data.pageIndex > that.data.pageCount) {
        that.setData({
          isLoadData: true,
          loadText: "已经到底了"
        });
      } else {
        that.getUserDiscountCoupon(that.data.type);
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      couponData: [],
      isHints: false, //无数据提示信息
      disabled: false,
      assetId: '',
      selectShopId: '',
      pageIndex: 1,
      pageSize: 10,
      pageCount: 1,
      loadText: "",
      isLoadData: false,
    }, function () {
      this.getUserDiscountCoupon(this.data.type);
    })
  },
})